package com.cndw.kungfu.event.model;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.cndw.kungfu.comm.CommInspection;
import com.cndw.kungfu.comm.FiledDel;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsCore;
import com.cndw.kungfu.config.ConstantsDayIntKey;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Union;
import com.cndw.kungfu.ext.LangUtil;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.CrossProxySerialize;
import com.cndw.kungfu.model.DataStaticDay;
import com.cndw.kungfu.model.goods.domain.SubPops;
import com.cndw.kungfu.model.pvp.war.WarCoreCenter;
import com.cndw.kungfu.model.sys.ChatMain;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.kungfu.vo.rankingvo.PlayerRankingVO;

public class PlayerLoginInitHandler implements Runnable {
	private Player player;
	private boolean isReg;
	private int lastLogin;

	public PlayerLoginInitHandler(Player player, boolean isReg) {
		lastLogin = player.getLastLogin();
		this.isReg = isReg;
		this.player = player;
	}

	@Override
	public void run() {

		try {
			boss();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void boss() {
		final int morningTime = TimeProcesser.getMorningTime();
		final int currentTime = TimeProcesser.getUnixTime();
		if (lastLogin <= morningTime || isReg) {
			if (!player.getDataInfo().getEveryDay().isLogAward()) {// 未領取過獎勵的才+
				if (morningTime - lastLogin < 86400) {
					player.getDataInfo().intDataSet(ConstantsIntKey.relogNum, player.getDataInfo().intDataGet(ConstantsIntKey.relogNum) % 7 + 1);
				} else {
					player.getDataInfo().intDataSet(ConstantsIntKey.relogNum, 1);
				}
			}
			// player.setTodayOnLine(0);// 清理今天登录时间

			// ------------------------
			// 初始化当天经验找回状态 2012-06-07 add by Skycat
			player.getDataInfo().initExpRetMap(player.getOffLineTime() < morningTime);

			if (!isReg) {
				player.getOffLineTime();
				if (player.getLevel() >= 50 && currentTime - player.getOffLineTime() >= 7 * 86400) {
					String title = LanguageLib.get("worldlevel.week.title");
					String content = LanguageLib.get("worldlevel.week.content");
					List<SubPops> attachment = new ArrayList<SubPops>();
					attachment.add(new SubPops(103527, 1, 0, 0));// 勇者回归礼包
					Context.getMessageServer().sendSysMail(player.getPlayerId(), player.getPlayerName(), title, content, attachment);
				}

			}
			if (DataStaticDay.getInstance().isLoser(player.getLevel())) {

				String title = LanguageLib.get("worldlevel.losslevel.title");
				String content = LanguageLib.get("worldlevel.losslevel.content");
				List<SubPops> attachment = new ArrayList<SubPops>();
				attachment.add(new SubPops(103528, 1, 0, 0));// 等级补偿礼包
				Context.getMessageServer().sendSysMail(player.getPlayerId(), player.getPlayerName(), title, content, attachment);

			}

		}

		// 下线打坐经验
		if (player.getLevel() >= ConstantsLevel.lv1OnlineExp && player.getLevel() != Constants.playerMaxLevel) {
			player.getDataInfo().intDataSet(ConstantsIntKey.beginDaZuo, player.getOffLineTime());
			Context.getGeneralServer().getOfflineExp(player);
		}

		if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.timesNoviec) < ConstantsModel.playerNoviceAwardTimes.length) {

			int haveTimes = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.timesNoviec);
			int needTime = ConstantsModel.playerNoviceAwardTimes[haveTimes];
			int begingTime = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.noviecAward);
			begingTime = begingTime == 0 ? currentTime : begingTime;
			int overTime = currentTime - begingTime;

			EventNotice eventNotice = new EventNotice("noviceAward", "loading");
			int nextTime = haveTimes + 1;
			eventNotice.put("awardId", nextTime);
			eventNotice.put("laveTime", needTime - overTime);
			eventNotice.put("awardTips", "");

			if (!isReg && lastLogin <= morningTime) {// 首次登录弹出这个
				eventNotice.put("showActivity", 1);
			}
			if (!isReg) {
				if (lastLogin > 0 && lastLogin <= ConstantsCore.getUpdateLastTime()) {
					eventNotice.put("showActivity", 2);
				}
			}

			eventNotice.broadcast(player.getPlayerId());

		}
		try {
			loginSendMsg();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			fixData(currentTime);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			int[] pubacct = CommInspection.pubacct(player);
			//pubacct = new int[] { 0, 0, 10 };
			if (pubacct[0] > 0 || pubacct[1] > 0 || pubacct[2] > 0) {
				EventNotice eventNotice = new EventNotice(ConstantsRadio.comm, ConstantsRadio.commPubacct);
				eventNotice.put("pubaccts", pubacct);
				eventNotice.broadcast(player.getPlayerId());
			}

			// String testMsg = CommInspection.taskCompleted(player, 1, "123",
			// 0);

		} catch (Exception e) {
			e.printStackTrace();
		}

		/**
		 * 上报数据
		 */
		if (!player.getDataInfo().isGmLogin()) {
			if (isReg) {
				QQDC.getInstance().reg(player);
			}
			QQDC.getInstance().login(player);
		}

	}

	private void loginSendMsg() {
		// 通知好友上线
		EventNotice eventNotice = new EventNotice("friend", "online");
		eventNotice.put("playerId", player.getPlayerId());
		eventNotice.put("playerName", player.getPlayerName());
		eventNotice.broadcast(player.getDataInfo().getFriendIds());

		// 上线通知
		int delay = 5;
		if (player.getLevel() > 10) {
			PlayerRankingVO ranking = Context.getGeneralServer().getPlayerRanking(player);

			if (ranking.getLevelRank() > 0 && ranking.getLevelRank() < 4) {
				ChatMain.systemMessageDelay(LanguageLib.get("ranking.level.online" + ranking.getLevelRank(), player.getPlayerName()), delay);
			}
			if (ranking.getAttackRank() > 0 && ranking.getAttackRank() < 4) {
				ChatMain.systemMessageDelay(LanguageLib.get("ranking.attack.online" + ranking.getAttackRank(), player.getPlayerName()), delay);
			}
			if (ranking.getDiscipleRank() > 0 && ranking.getDiscipleRank() < 4) {
				ChatMain.systemMessageDelay(LanguageLib.get("ranking.disciple.online" + ranking.getDiscipleRank(), player.getPlayerName()), delay);
			}
			if (player.getUnionId() >0 && ranking.getUnionRank() > 0 && ranking.getUnionRank() < 4 ) {
				Union union = Context.getUnionServer().getUnionById(player.getUnionId());
				if (union != null && union.getPlayerId() == player.getPlayerId()) {
					ChatMain.systemMessageDelay(LanguageLib.get("ranking.union.online" + ranking.getUnionRank(), player.getPlayerName()), delay);
				}
			}

			if (ranking.getTowerRank() > 0 && ranking.getTowerRank() < 4) {
				ChatMain.systemMessageDelay(LanguageLib.get("ranking.tower.online" + ranking.getTowerRank(), player.getPlayerName()), delay);
			}
		}
		int petModeId = player.getDataInfo().getPet() == null ? 0 : player.getDataInfo().getPet().getModeId();

		String petLangKey = null;
		if (petModeId == 3) {// 火麒麟上线提示
			petLangKey = "chat.board.pet";
		} else if (petModeId >= 11 && petModeId <= 13) {// 神·白虎上线提示
			petLangKey = "chat.board.pettiger";
		} else if (petModeId >= 14 && petModeId <= 16) {// 神·玄武上线提示
			petLangKey = "chat.board.petturtle";
		}
		if (petLangKey != null) {
			ChatMain.systemMessageDelay(LanguageLib.get(petLangKey, LangUtil.makeNameLink(player)), delay);

		}

		if (player.getDataInfo().getTitles().contains(67) || player.getDataInfo().getTitles().contains(68)) {// 花魁情圣、花之舞者上线广播
			WarCoreCenter.chatMsssageDelay(
					0,
					10,
					LanguageLib.get(player.getDataInfo().getTitles().contains(67) ? "holiday.mmflower.login1" : "holiday.mmflower.login2",
							ConstantsConfig.getSysCgSvrId(), player.getPlayerName()));
		}

		int hd = CrossProxySerialize.getInstance().worldHidGet(player.getPlayerId());
		if (hd == 1 || hd == 2) {
			int headCycle = CrossProxySerialize.getInstance().getHeadCycle();
			headCycle = headCycle <= 0 ? 1 : headCycle;
			WarCoreCenter.chatMsssageDelay(0, 10,
					LanguageLib.get(hd == 1 ? "chat.board.world1" : "chat.board.world2", ConstantsConfig.getSysCgSvrId(), player.getPlayerName(), headCycle));
		}
	}

	private void fixData(int currentTime) {

		if (!isReg) {
			try {
				int xxxTime = TimeProcesser.getUnixTimeByString("2012-5-23 14:00:00");
				if (lastLogin < xxxTime) {
					if (player.getDataInfo().intDataGet(ConstantsIntKey.payTrue) == 0) {// 修正我的充值标识
						if (Context.getBusinessServer().selectPayGoldSumOnlyQQPay(player.getPlayerId()) > 0) {
							player.getDataInfo().intDataSet(ConstantsIntKey.payTrue, 1);
							player.getDataInfo().commitSync();
						}
					}
				}

				if (player.stateContains(Constants.playerState32_vipAdd)// 清理vip标记
						&& player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.vipAward) + 1800 <= currentTime) {

					player.stateRemove(Constants.playerState32_vipAdd);
					Context.getPlayerServer().clacProperties(player);
				}
				// ------------------------
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				int xxxTime = TimeProcesser.getUnixTimeByString("2012-11-6 09:00:00");
				if (lastLogin < xxxTime) {

					Context.getGeneralServer().removeTitle(player.getPlayerId(), 63);
					Context.getGeneralServer().removeTitle(player.getPlayerId(), 64);
					Context.getGeneralServer().removeTitle(player.getPlayerId(), 65);
					Context.getGeneralServer().removeTitle(player.getPlayerId(), 66);

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				int xxxTime = TimeProcesser.getUnixTimeByString("2012-10-23 09:00:00");
				if (lastLogin < xxxTime) {
					Field[] fields = ConstantsIntKey.class.getFields();
					StringBuilder sb = new StringBuilder();
					for (Field field : fields) {
						if (field.isAnnotationPresent(FiledDel.class)) {
							if (player.getDataInfo().intDataGet(field.getName()) > 0) {
								if (sb.length() > 0 ) {
									sb.append(',');
								}
								sb.append(field.getName()).append('|').append(player.getDataInfo().intDataGet(field.getName()));
								player.getDataInfo().intDataRemove(field.getName());
							}
						}
					}
					if (sb.length() > 0) {
						LogUtil.getSystem().info("datainfo clear : "+player.getAccountName()+" : " + sb.toString());
						player.getDataInfo().commitSync();
						LogServer.recordLog(player, ConstantsLog.player, 30031, sb.toString());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}
}
